package com.xpec.c4.db.util;

import java.util.Random;

public class RandomUtil extends Random {

	/**
	 *
	 */
	private static final long serialVersionUID = 8396259286647654881L;

	/**
	 * 随机出一个指定的数字内的任意正整数并返回该整数的字符串，该方法通过高位补零保证长度原来的字符串一致
	 * 
	 * @param n
	 * @return author: zhongzhengkai date: 2012 2012-8-14 下午03:52:17
	 */
	public String nextIntString(int n) {
		String in = String.valueOf(n);
		int len = in.length();
		if (n <= 0)
			throw new IllegalArgumentException("n must be positive");

		if ((n & -n) == n) // i.e., n is a power of 2
			return String.valueOf(((n * (long) next(31)) >> 31));

		int bits, val;
		do {
			bits = next(31);
			val = bits % n;
		} while (bits - val + (n - 1) < 0);

		String out = String.valueOf(val);
		StringBuilder sb = new StringBuilder();
		if (out.length() < len) {
			// 算出高位要补几个零
			int high = len - out.length();
			for (int i = 0; i < high; i++) {
				sb.append("0");
			}
		}
		sb.append(val);

		return sb.toString();
	}

	/**
	 * 给传进来的int值高位补零，默认最大不超过4位（如3转为0003的字符串）
	 * @param n
	 * @return
	 * author: zhongzhengkai date: 2012 2012-8-14 下午06:53:28
	 */
	public String intToString(int n) {
		String in = String.valueOf(n);
		int len = in.length();
		StringBuilder sb = new StringBuilder();
		if (len < 4) {
			// 算出高位要补几个零
			int high = 4 - len;
			for (int i = 0; i < high; i++) {
				sb.append("0");
			}
		}
		sb.append(n);

		return sb.toString();
	}
	

	/**
	 * @param n 位數
	 * @return
	 * 隨機輸出n位數的亂數+大寫字母
	 * 
	 */
	public String nextString(int len) {
		if (len <= 0)
			throw new IllegalArgumentException("n must be positive");

		StringBuilder sb = new StringBuilder();
		Integer rand = 0;
		
		for(int index = 0; index < len ; index ++){
			rand = nextInt(36);
			if(rand <10){
				sb.append(rand.toString());
			}else{
				char b = 'A';
				b = (char) (b + rand - 10);
				sb.append(b);
			}
		}

		return sb.toString();
	}
	
}
